import fetch from 'node-fetch';
import {createLogger} from "./Logger.js";


export class GitLabClient {
    /**
     * @param {string} token 认证 token PRIVATE-TOKEN
     * @param {boolean} verbose 打印日志
     */
    constructor(token, verbose=false) {
        this.token = token;
        this.baseUrl = 'http://gitlab.inzwc.com/';
        this.verbose = verbose;
        this.logger = createLogger("HTTP");
    }

    /**
     * 发起请求（带 data）
     * @param {string} pathOrUrl API 路径或完整 URL
     * @param {string} method 请求方法
     * @param {object|null} body 请求体
     * @returns {Promise<any>}
     */
    async request(pathOrUrl, method = 'GET', body = null) {
        const url = pathOrUrl.startsWith('http') ? pathOrUrl : `${this.baseUrl}${pathOrUrl}`;
        const options = {
            method,
            headers: {
                'Accept': 'application/json, text/plain, */*',
                'Cache-Control': 'no-cache',
                'Connection': 'keep-alive',
                'Pragma': 'no-cache',
                'Referer': this.baseUrl,
                'Host': 'gitlab.inzwc.com',
                'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36',
                'PRIVATE-TOKEN': `${this.token}`,
            },
        };
        if (body) {
            options.headers['Content-Type'] = 'application/json';
            options.body = JSON.stringify(body);
        }

        if (this.verbose) {
            this.logger.info(
                `➡️ 请求:\n url=${url}\n method=${method}\n headers=${JSON.stringify(options.headers)}\n body=${options.body || '{}'}`
            );
        }

        const res = await fetch(url.toString(), options);

        const resText = await res.text();
        let resData;
        try {
            resData = JSON.parse(resText);
        } catch {
            resData = resText;
        }
        if (this.verbose) {
            this.logger.info(
                `⬅️ 响应:\n url=${url}\n status=${res.status}\n body=${JSON.stringify(resData)}`
            );
        }
        if (!res.ok) {
            this.logger.info(
                `➡️ 请求:\n url=${url}\n method=${method}\n headers=${JSON.stringify(options.headers)}\n body=${options.body || '{}'}`
            );
            this.logger.info(
                `⬅️ 响应:\n url=${url}\n status=${res.status}\n body=${JSON.stringify(resData)}`
            );
            throw new Error(`请求失败，状态码 ${res.status}`);
        }
        return resData;
    }

    /**
     *  创建MR 并且打上CR标签
     * @param {Object} body CR参数
     * @param {Object} pocketId git项目
     *
     */
    async mergeRequestsAndCr(pocketId,body) {
        return this.request(`api/v4/projects/${pocketId}/merge_requests`,'POST',body);
    }
    /**
     *  已有MR 打上CR标签
     * @param {Object} body CR参数
     * @param {Object} mId 已有MR ID
     * @param {Object} pocketId git项目
     *
     */
    async mergeRequestsAndCrByMrId(pocketId,mId,body) {
        return this.request(`api/v4/projects/${pocketId}/merge_requests/${mId}`,'PUT',body);
    }

}
/**
 *
 */
export function newGitLabClient(token,verbose) {
    return new GitLabClient(token,verbose);
}


